package com.yourenbang.lingyun.transaction.job.handler;

import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import com.yourenbang.lingyun.constants.Constant;
import com.yourenbang.lingyun.constants.enums.PlatNoEnums;
import com.yourenbang.lingyun.constants.enums.WithDrawStatusEnum;
import com.yourenbang.lingyun.constants.enums.pay.PayTypeEnum;
import com.yourenbang.lingyun.constants.enums.table.FundAccountWithdrawPaymentBillEnum;
import com.yourenbang.lingyun.core.util.BizAssertUtils;
import com.yourenbang.lingyun.core.util.date.DateFormat;
import com.yourenbang.lingyun.domain.FundAccountWithdrawPaymentBill;
import com.yourenbang.lingyun.domain.FundAccountWithdrawPaymentBillExample;
import com.yourenbang.lingyun.mapper.FundAccountWithdrawPaymentBillMapper;
import com.yourenbang.lingyun.mapper.PayChannelMapper;
import com.yourenbang.lingyun.transaction.mapper.TransactionFundAccountWithdrawPaymentMapper;
import com.yourenbang.lingyun.transaction.web.domain.dto.fund.WithdrawSettleBillDTO;
import com.yourenbang.lingyun.transaction.web.domain.vo.fund.T1WithdrawBillVO;
import com.yourenbang.transaction.api.service.pay.PayTypeApiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Component
@Slf4j
public class WithdrawSettleHandler {

    @Resource
    private PayTypeApiService payTypeApiService;
    @Resource
    private PayChannelMapper payChannelMapper;
    @Resource
    private TransactionFundAccountWithdrawPaymentMapper transactionFundAccountWithdrawPaymentMapper;
    @Resource
    private FundAccountWithdrawPaymentBillMapper fundAccountWithdrawPaymentBillMapper;


    /**
     * 统计日结定时任务
     */
    @XxlJob("withdrawSettleBillHandler")
    public ReturnT<String> withdrawSettleBillHandler(String param) throws Exception {

        XxlJobLogger.log("【统计日结定时任务】任务开始。。。，入参：{}", param);

        String batchNumber = DateFormat.DATE_COMPACT.format(LocalDateTime.now().minusDays(1));
        List<Short> platNos = new ArrayList<>();
        if (StringUtils.isNotBlank(param)) {
            WithdrawSettleBillDTO withdrawSettleBillDTO = JSONObject.parseObject(param, WithdrawSettleBillDTO.class);
            if (StringUtils.isNotBlank(withdrawSettleBillDTO.getBatchNumber())) {
                batchNumber = withdrawSettleBillDTO.getBatchNumber();
            }
            if(Objects.nonNull(withdrawSettleBillDTO.getPlatNos())){
                platNos = withdrawSettleBillDTO.getPlatNos();
            }
        }
        if (CollectionUtils.isEmpty(platNos)) {
            platNos.add(PlatNoEnums.KLKS.getCode());
            platNos.add(PlatNoEnums.YXY.getCode());
        }

        //循环平台
        for (Short platNo : platNos) {
            //查询所有该批次号的提现记录状态为初始的  区分平台, 支付渠道
            List<T1WithdrawBillVO> t1WithdrawBillVOS = transactionFundAccountWithdrawPaymentMapper.queryT1WithdrawAlipayBill(platNo,
                    WithDrawStatusEnum.WITHDRAW_STATUS_INIT.getCode(), batchNumber);
            List<T1WithdrawBillVO> t1WithdrawBillVOSBank = transactionFundAccountWithdrawPaymentMapper.queryT1WithdrawBankBill(platNo,
                    WithDrawStatusEnum.WITHDRAW_STATUS_INIT.getCode(), batchNumber);
            t1WithdrawBillVOS.addAll(t1WithdrawBillVOSBank);
            //循环渠道
            for (T1WithdrawBillVO t1WithdrawBillVO : t1WithdrawBillVOS) {
                if (t1WithdrawBillVO.getTotalCount() == 0) {
                    continue;
                }
                FundAccountWithdrawPaymentBill fundAccountWithdrawPaymentBill = new FundAccountWithdrawPaymentBill();
                fundAccountWithdrawPaymentBill.setBatchNumber(batchNumber);
                fundAccountWithdrawPaymentBill.setAmount(t1WithdrawBillVO.getAmount());
                fundAccountWithdrawPaymentBill.setActualAmount(BigDecimal.ZERO);
                fundAccountWithdrawPaymentBill.setTotalCount(t1WithdrawBillVO.getTotalCount());
                fundAccountWithdrawPaymentBill.setTotalActualCount(0);

                if (PayTypeEnum.isBankCardEnum(t1WithdrawBillVO.getPayGetway()) || PayTypeEnum.BANK_CARD_PAY.isEquals(t1WithdrawBillVO.getPayGetway())) {
                    fundAccountWithdrawPaymentBill.setPayChannelType(FundAccountWithdrawPaymentBillEnum.PayChannelTypeEnum.BANK_CARD.getCode());
                } else if (PayTypeEnum.ALIPAY.isEquals(t1WithdrawBillVO.getPayGetway())) {
                    fundAccountWithdrawPaymentBill.setPayChannelType(FundAccountWithdrawPaymentBillEnum.PayChannelTypeEnum.ALIPAY.getCode());
                } else {
                    log.error("支付通道不存在:{}", t1WithdrawBillVO.toString());
                    XxlJobLogger.log("支付通道不存在", t1WithdrawBillVO.getPayGetway());
                    continue;
                }

                fundAccountWithdrawPaymentBill.setPlatNo(platNo);
                fundAccountWithdrawPaymentBill.setPayStatus(FundAccountWithdrawPaymentBillEnum.PayStatusEnum.WAIT_PAY.getCode());

                FundAccountWithdrawPaymentBillExample fundAccountWithdrawPaymentBillExample = new FundAccountWithdrawPaymentBillExample();
                fundAccountWithdrawPaymentBillExample.createCriteria().andPlatNoEqualTo(fundAccountWithdrawPaymentBill.getPlatNo())
                        .andPayChannelTypeEqualTo(fundAccountWithdrawPaymentBill.getPayChannelType()).andIsDelEqualTo(Constant.NORMAL)
                .andBatchNumberEqualTo(batchNumber);
                List<FundAccountWithdrawPaymentBill> fundAccountWithdrawPaymentBills = fundAccountWithdrawPaymentBillMapper.selectByExample(fundAccountWithdrawPaymentBillExample);
                if (CollectionUtils.isEmpty(fundAccountWithdrawPaymentBills)) {
                    XxlJobLogger.log("插入日结账单:{}",fundAccountWithdrawPaymentBill.toString());
                    int i = fundAccountWithdrawPaymentBillMapper.insertSelective(fundAccountWithdrawPaymentBill);
                    BizAssertUtils.assertOne(i, "插入日结账单失败");
                } else {
                    //存在且未发放则更新
                    if (FundAccountWithdrawPaymentBillEnum.PayStatusEnum.WAIT_PAY.isEquals(fundAccountWithdrawPaymentBills.get(0).getPayStatus())) {
                        fundAccountWithdrawPaymentBill.setFundAccountWithdrawPaymentBillId(fundAccountWithdrawPaymentBills.get(0).getFundAccountWithdrawPaymentBillId());
                        XxlJobLogger.log("更新日结账单:{}",fundAccountWithdrawPaymentBill.toString());
                        int i = fundAccountWithdrawPaymentBillMapper.updateByPrimaryKeySelective(fundAccountWithdrawPaymentBill);
                        BizAssertUtils.assertOne(i, "更新日结账单失败");
                    }
                }
            }
        }
        return ReturnT.SUCCESS;
    }
}
